<script>
  // name 属性用于 App.vue 根组件中的 KeepAlive 组件缓存，作为include属性值
  export default { name: "home" }
</script>
<script setup>
  import { ref, watch, computed, onActivated } from 'vue'
  import useHomeStore from '@/stores/modules/home'
  import { useScroll } from '@/hooks/useScroll'
  import HomeNavBar from './cpns/home-nav-bar.vue'
  import HomeSearchBox from './cpns/home-search-box.vue'
  import HomeCategories from './cpns/home-categories.vue'
  import HomeContent from './cpns/home-content.vue'
  import SearchBar from '@/components/search-bar/search-bar.vue'

  // 发送网络请求
  const homeStore = useHomeStore()
  homeStore.fetchHotSuggestsData()
  homeStore.fetchCategoriesData()
  homeStore.fetchHouseListData()

  const homeRef = ref()
  const { isReachBottom, scrollTop } = useScroll(homeRef)
  // 侦听 isReachBottom 响应式对象值的变化
  watch([isReachBottom], (newValue) => {
    // 如果页面滚动到底部，执行相应的操作
    if(newValue[0]) {
      // fetchHouseListData() 为异步函数
      /* 
      异步函数：默认情况下，会将函数的返回值作为一个 Promise 对象的 resolve() 的参数，
      并将该 Promise对象返回
      */
     homeStore.fetchHouseListData().then(() => {
       // 当执行完相应的操作后，再将标识 isReachBottom 的值设置为 false
       isReachBottom.value = false
      })
    }
  })

  // 搜索框显示/隐藏-控制
  // 方式1：侦听属性
  // const isShowSearchBar = ref(false)
  // watch(scrollTop, (newTop) => {
  //   isShowSearchBar.value = newTop >= 100
  // })
  // 方式2：计算属性
  // 计算属性有数据缓存，只有当依赖的对象发生变化时，才会执行相应操作
  const isShowSearchBar = computed(() => {
    return scrollTop.value >= 350
  })

  // 跳转回 home 时，保留原来的浏览位置
  // onActivated 和 onDeactivated 只在被 keep-alive 包裹的组件中才有效
  onActivated(() => {
    homeRef.value?.scrollTo({
      top: scrollTop.value
    })
  })
</script>

<template>
  <div class="home" ref="homeRef">
    <!-- 标题组件 -->
    <home-nav-bar />
    
    <!-- 大图 -->
    <div class="banner">
      <img src="@/assets/img/home/banner.webp" alt="">
    </div>

    <!-- 查找信息组件 -->
    <home-search-box />

    <!-- 推荐类别 -->
    <home-categories />

    <!-- 搜索框 -->
    <div class="search-bar" v-if="isShowSearchBar">
      <search-bar :start-date="'09.19'" :end-date="'09.20'"/>
    </div>

    <!-- 房屋列表 -->
    <home-content />
  </div>
</template>

<style lang="less" scoped>
  .home {
    height: 100vh;
    overflow-y: auto;
    box-sizing: border-box;
    padding-bottom: 50px;
  }

  .banner img {
    width: 100%;
  }

  .search-bar {
    position: fixed;
    // 设置元素层级，避免被遮盖
    z-index: 10;
    top: 0;
    left: 0;
    right: 0;
    height: 45px;
    padding: 16px 16px 10px;
    background-color: #fff;
  }
</style>